<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useRouterPush } from '@/hooks/common/router';
import {
  createCurveDefinition,
  deleteCurveDefinition,
  fetchCurveDefinitions,
  updateCurveDefinition
} from '@/service/api/curve';

const { routerPushByKey } = useRouterPush();

// 表格数据
const loading = ref(false);
const dataSource = ref<Api.Curve.CurveDefinition[]>([]);

// 搜索参数
const searchParams = reactive({
  curveName: '',
  curveType: '',
  currencyCode: ''
});

// 弹窗状态
const modalVisible = ref(false);
const modalTitle = ref('');
const modalLoading = ref(false);
const editingId = ref<number | null>(null);

// 表单数据
const formData = reactive<Api.Curve.CurveDefinitionDTO>({
  curveName: '',
  description: '',
  curveType: '',
  currencyCode: ''
});

// 表格列定义
const columns = [
  {
    title: '货币代码',
    dataIndex: 'currencyCode',
    key: 'currencyCode',
    width: 120
  },
  {
    title: '曲线名称',
    dataIndex: 'curveName',
    key: 'curveName',
    width: 350
  },
  {
    title: '曲线类型',
    dataIndex: 'curveType',
    key: 'curveType',
    width: 150
  },

  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right' as const
  }
];

// 获取数据
async function getData() {
  loading.value = true;
  try {
    const { data, error } = await fetchCurveDefinitions();
    if (data) {
      let filteredData = data;

      // 前端筛选
      if (searchParams.curveName) {
        filteredData = filteredData.filter(item =>
          item.curveName.toLowerCase().includes(searchParams.curveName.toLowerCase())
        );
      }
      if (searchParams.curveType) {
        filteredData = filteredData.filter(item =>
          item.curveType?.toLowerCase().includes(searchParams.curveType.toLowerCase())
        );
      }
      if (searchParams.currencyCode) {
        filteredData = filteredData.filter(item =>
          item.currencyCode?.toLowerCase().includes(searchParams.currencyCode.toLowerCase())
        );
      }

      dataSource.value = filteredData;
    } else if (error) {
      window.$message?.error(`获取曲线列表失败：${error.message}`);
    }
  } catch (error) {
    window.$message?.error(`获取曲线列表失败：${(error as any).message}`);
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  getData();
}

// 重置搜索
function handleReset() {
  Object.assign(searchParams, {
    curveName: '',
    curveType: '',
    currencyCode: ''
  });
  getData();
}

// 新建曲线
function handleAdd() {
  modalTitle.value = '新建曲线定义';
  editingId.value = null;
  Object.assign(formData, {
    curveName: '',
    description: '',
    curveType: '',
    currencyCode: ''
  });
  modalVisible.value = true;
}

// 编辑曲线
function handleEdit(record: Api.Curve.CurveDefinition) {
  modalTitle.value = '编辑曲线定义';
  editingId.value = record.curveId;
  Object.assign(formData, {
    curveName: record.curveName,
    description: record.description || '',
    curveType: record.curveType,
    currencyCode: record.currencyCode
  });
  modalVisible.value = true;
}

// 删除曲线
function handleDelete(record: Api.Curve.CurveDefinition) {
  window.$modal?.confirm({
    title: '确认删除',
    content: `确定要删除曲线"${record.curveName}"吗？`,
    onOk: async () => {
      try {
        const { error } = await deleteCurveDefinition(record.curveId);
        if (!error) {
          window.$message?.success('删除成功');
          getData();
        } else {
          window.$message?.error(`删除失败：${error.message}`);
        }
      } catch (error) {
        window.$message?.error(`删除失败：${(error as any).message}`);
      }
    }
  });
}

// 查看详情
function handleViewDetail(record: Api.Curve.CurveDefinition) {
  routerPushByKey('valuation_curve-detail', {
    query: { curveId: record.curveId.toString(), curveName: record.curveName }
  });
}

// 保存表单
async function handleSave() {
  modalLoading.value = true;
  try {
    if (editingId.value) {
      // 编辑
      const { error } = await updateCurveDefinition(editingId.value, formData);
      if (!error) {
        window.$message?.success('更新成功');
        modalVisible.value = false;
        getData();
      } else {
        window.$message?.error(`更新失败：${error.message}`);
      }
    } else {
      // 新建
      const { error } = await createCurveDefinition(formData);
      if (!error) {
        window.$message?.success('创建成功');
        modalVisible.value = false;
        getData();
      } else {
        window.$message?.error(`创建失败：${error.message}`);
      }
    }
  } catch (error) {
    window.$message?.error(`操作失败：${(error as any).message}`);
  } finally {
    modalLoading.value = false;
  }
}

// 取消弹窗
function handleCancel() {
  modalVisible.value = false;
}

// 初始化
onMounted(() => {
  getData();
});
</script>

<template>
  <div>
    <!-- 搜索区域 -->
    <ACard class="mb-4">
      <AForm layout="inline">
        <AFormItem label="曲线名称">
          <AInput
            v-model:value="searchParams.curveName"
            placeholder="请输入曲线名称"
            allow-clear
            @press-enter="handleSearch"
          />
        </AFormItem>
        <AFormItem label="曲线类型">
          <AInput
            v-model:value="searchParams.curveType"
            placeholder="请输入曲线类型"
            allow-clear
            @press-enter="handleSearch"
          />
        </AFormItem>
        <AFormItem label="货币代码">
          <AInput
            v-model:value="searchParams.currencyCode"
            placeholder="请输入货币代码"
            allow-clear
            @press-enter="handleSearch"
          />
        </AFormItem>
        <AFormItem>
          <ASpace>
            <AButton type="primary" @click="handleSearch">
              <template #icon>
                <icon-ic-round-search class="text-icon" />
              </template>
              搜索
            </AButton>
            <AButton @click="handleReset">
              <template #icon>
                <icon-ic-round-refresh class="text-icon" />
              </template>
              重置
            </AButton>
          </ASpace>
        </AFormItem>
        <AFormItem>
          <AButton type="primary" @click="handleAdd">
            <template #icon>
              <icon-ic-round-add class="text-icon" />
            </template>
            新建曲线
          </AButton>
        </AFormItem>
      </AForm>
    </ACard>
    <!-- 操作区域 -->
    <ACard>
      <!-- 表格 -->
      <ATable
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total: number) => `共 ${total} 条记录`,
          pageSizeOptions: ['10', '20', '50', '100'],
          defaultPageSize: 20
        }"
        row-key="curveId"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" size="small" @click="handleViewDetail(record as Api.Curve.CurveDefinition)">
                查看详情
              </AButton>
              <AButton type="link" size="small" @click="handleEdit(record as Api.Curve.CurveDefinition)">编辑</AButton>
              <AButton type="link" size="small" danger @click="handleDelete(record as Api.Curve.CurveDefinition)">
                删除
              </AButton>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新建/编辑弹窗 -->
    <AModal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <AForm :model="formData" layout="vertical">
        <AFormItem label="曲线名称" name="curveName" :rules="[{ required: true, message: '请输入曲线名称' }]">
          <AInput v-model:value="formData.curveName" placeholder="请输入曲线名称" />
        </AFormItem>
        <AFormItem label="曲线类型" name="curveType" :rules="[{ required: true, message: '请输入曲线类型' }]">
          <ASelect v-model:value="formData.curveType" placeholder="请选择曲线类型">
            <ASelectOption value="INTEREST_RATE">利率曲线</ASelectOption>
            <ASelectOption value="CREDIT_SPREAD">信用利差曲线</ASelectOption>
            <ASelectOption value="VOLATILITY">波动率曲线</ASelectOption>
            <ASelectOption value="FORWARD">远期曲线</ASelectOption>
          </ASelect>
        </AFormItem>
        <AFormItem label="货币代码" name="currencyCode" :rules="[{ required: true, message: '请输入货币代码' }]">
          <ASelect v-model:value="formData.currencyCode" placeholder="请选择货币代码">
            <ASelectOption value="CNY">人民币(CNY)</ASelectOption>
            <ASelectOption value="USD">美元(USD)</ASelectOption>
            <ASelectOption value="EUR">欧元(EUR)</ASelectOption>
            <ASelectOption value="JPY">日元(JPY)</ASelectOption>
            <ASelectOption value="GBP">英镑(GBP)</ASelectOption>
          </ASelect>
        </AFormItem>
        <AFormItem label="描述" name="description">
          <ATextarea v-model:value="formData.description" placeholder="请输入曲线描述" :rows="3" />
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped>
.text-icon {
  font-size: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 表格行间距优化 */
:deep(.ant-table-tbody > tr > .ant-table-cell) {
  padding: 8px 16px !important;
}

:deep(.ant-table-thead > tr > th) {
  padding: 8px 16px !important;
}
</style>
